import { addRule, removeRule, rule, updateRule } from '@/services/auth/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ColumnsState, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState } from 'react';
import { faL } from '@fortawesome/free-solid-svg-icons';
import EditForm from './components/EditForm';
import { pagedAPi,activeApi } from '@/services/channel/spapi_api';
import dayjs from 'dayjs';
import { formatToLocalTime,toUTC } from '@/utils/time';


const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<ApiService>();
  const [selectedRowsState, setSelectedRows] = useState<ApiService[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
const makeActive = (id: string, status: number) => {
  Modal.confirm({
    title: intl.formatMessage({ id: 'pages.confirm.title' }),
    content: intl.formatMessage(
      { id: 'pages.confirm.content' },
      { action: intl.formatMessage({ id: status === 0 ? 'pages.activate' : 'pages.deactivate' }) }
    ),
    okText: intl.formatMessage({ id: 'pages.confirm.okText' }),
    cancelText: intl.formatMessage({ id: 'pages.confirm.cancelText' }),
    onOk: async () => {
      const hide = message.loading(intl.formatMessage({ id: 'pages.processing' }));
      try {
        await activeApi({ asId: id, asStatus: status });
        hide();
        message.success(
          intl.formatMessage({
            id: status === 0 ? 'pages.success.activate' : 'pages.success.deactivate'
          })
        );
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } catch (error) {
        hide();
        message.error(intl.formatMessage({ id: 'request.error.retry' }));
      }
    },
  });
};

  const columns: ProColumns<ApiService>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.spApi.apiCode"
          defaultMessage="API Code"
        />
      ),
      dataIndex: 'asCode',
    },
    {
      title: <FormattedMessage id="pages.spApi.apiName" defaultMessage="API Name" />,
      dataIndex: 'asName',
    },

    {
      title: <FormattedMessage id="pages.spApi.status" defaultMessage="Status" />,
      dataIndex: 'asStatus',
      hideInForm: true,
      valueEnum: {
        "1": {
          text: (
            <FormattedMessage id="pages.inactive" defaultMessage="Inactive" />
          ),
          status: 'Error',
        },
        "0": {
          text: (
            <FormattedMessage id="pages.active" defaultMessage="Active" />
          ),
          status: 'Success',
        },

      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.spApi.address"
          defaultMessage="API Address"
        />
      ),
      dataIndex: 'asAddress',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.createTime"
          defaultMessage="Create Time"
        />
      ),
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateRange',
      hideInForm: true,
      search: {
        transform: (value) => ({
          startTime: toUTC(value[0]),
          endTime: toUTC(value[1],true)
        })
      },
      render: (_, record) => {
        return formatToLocalTime(record.createTime);
      }
    },
    {
      title: (
        <FormattedMessage
          id="pages.updateTime"
          defaultMessage="updateTime"
        />
      ),
      dataIndex: 'updateTime',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      key: 'updateTime'
    },

    {
      title: <FormattedMessage id="pages.operating" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            makeActive(record.asId,record.asStatus);
            setCurrentRow(record);
          }}
        >
          {record.asStatus == '1' ? (
            <FormattedMessage id="pages.active" defaultMessage="Active" />
          ) : (
            <FormattedMessage id="pages.inactive" defaultMessage="Inactive" />
          )}
        </a>,
        <a key="edit" onClick={() => {
          setCurrentRow(record);
          handleUpdateModalOpen(true); // 打开编辑弹窗
        }}>
          <FormattedMessage
            id="pages.edit"
            defaultMessage="Edit"
          />
        </a>,
      ],
    },
  ];
  const [columnsStateMap, setColumnsStateMap] = useState<
    Record<string, ColumnsState>
  >({
    updateTime: {
      show: false,
    },
  });
  return (
    <div>
      <ProTable<ApiService, API.PageParams>
        headerTitle={intl.formatMessage({
          id: "pages.searchTable.title",
          defaultMessage: "Enquiry form",
        })}
        actionRef={actionRef}
        rowKey={(record, index) => `row-${index}`}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined />{" "}
            <FormattedMessage id="pages.spApi.new" defaultMessage="New" />
          </Button>,
        ]}
        request={pagedAPi}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
      />

      <EditForm
        visible={createModalOpen}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSuccess={function (): void {
          handleModalOpen(false);
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      />
      {/* 编辑表单 */}
      {currentRow && (
        <EditForm
          visible={updateModalOpen}
          values={currentRow}
          onCancel={() => {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
          }}
          onSuccess={() => {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          }}
        />
      )}
    </div>
  );
};

export default TableList;
